#include "stdafx.h"
#include "GraphicalCutit.hpp"
#include "../environment/Map.hpp"

namespace graphicalactors
{

GraphicalCutit::GraphicalCutit( const irr::core::vector3df& _Pos ) :
    m_id(0),
    m_age(0),  
    m_position(_Pos),
    m_radius(20.0f),
    m_entities()
{
    CONNECT( Event::EVENT_CHANGE_POSITION, &GraphicalCutit::onReceiveChangePosition);
}

GraphicalCutit::~GraphicalCutit()
{
    Event::EventManager::getSingleton().destroyAllConnections( this );

    for ( std::vector< GraphicalEntity * >::iterator it_entity = m_entities.begin();
        it_entity != m_entities.end();
        ++it_entity)
    {
        delete (*it_entity);
    }
    m_entities.clear();
}

void GraphicalCutit::init( irr::video::IVideoDriver * _driver, irr::scene::ISceneManager * _sceneManager, boost::uint8_t _baseAge )
{
    m_age = _baseAge;

    GraphicalEntity * entity = NULL;
    entity = new GraphicalEntity();
    entity->init( _driver, _sceneManager, m_position, "../media/models/sphere.mesh", "../media/textures/head.bmp" );
    m_entities.push_back( entity );
    for ( boost::uint8_t i = 0; i < m_age; ++i )
    {
        entity = new GraphicalEntity();
        entity->init( _driver, _sceneManager, m_position, "../media/models/sphere.mesh", "../media/textures/red.bmp" );
        m_entities.push_back( entity );
    }
}

void GraphicalCutit::draw( irr::core::vector3df& _newPosition )
{
    irr::core::vector3df direction(m_position - _newPosition);
    direction.normalize();

    m_position = _newPosition;

    for ( std::vector< GraphicalEntity * >::iterator it_entity = m_entities.begin();
        it_entity != m_entities.end();
        ++it_entity)
    {
        (*it_entity)->setPosition( _newPosition );
        
        _newPosition += direction * m_radius;
    }
}

void GraphicalCutit::onReceiveChangePosition(boost::shared_ptr< Event::EventBase > _evt)
{
    GET_REAL_EVENT_TYPE( Event::EventChangePosition, evt, _evt );

    if ( evt->getIdChanged() == m_id )
    {
        draw( evt->getNewPosition() );
    }
}

}